package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetMealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetMealDishService;
import com.itheima.reggie.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author DL5O
 * @version 1.0
 */
@Service
@Slf4j
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {

    @Autowired
    SetMealDishService setMealDishService;
    @Autowired
    CategoryService categoryService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1.保存setMeal的信息
        this.save(setmealDto);

        //2.获取setmealDishes 数组，并进行处理，将每个元素都设置上SetmealId
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setMealDishService.saveBatch(setmealDishes);
        log.info("保存成功..");
    }

    /**
     * 根据page，pageSize获取分页
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<SetmealDto> getPage(Integer page, Integer pageSize,String name) {
        //1.创建分页构造器
        Page<Setmeal> setMealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setMealDtoPage = new Page<>();

        //构造模糊查询条件
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);

        //2.进行分页查询
        this.page(setMealPage,qw);

        //3.进行值拷贝，把setMealPage中除了records
        BeanUtils.copyProperties(setMealPage, setMealDtoPage, "records");

        //4.取出对应的setMealPage中的records
        List<Setmeal> records = setMealPage.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //5.进行值拷贝
            BeanUtils.copyProperties(item, setmealDto);

            //6.通过categoryId
            Category category = categoryService.getById(item.getCategoryId());

            //7.将category中的name设置给setmealDto
            setmealDto.setCategoryName(category.getName());

            return setmealDto;
        }).collect(Collectors.toList());

        //8.将list赋给 setMealDtoPage的records
        setMealDtoPage.setRecords(list);
        return setMealDtoPage;
    }

    /**
     * 删除套餐，同时删除套餐和菜品的关联
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //1.查询套餐状态，确定是否可用删除
        //select count(*) from setmeal where id in(1,2,3,4,5) and status = 1;
        //如果统计出来的count > 0 那么就是不可删除的

        //编写sql
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);//id in (ids集合中的数据)
        queryWrapper.eq(Setmeal::getStatus,1);//起售状态为1

        //2.如果不能删除，抛出一个业务异常
        int count = this.count(queryWrapper);
        if(count > 0){
            //有套餐在售卖中
            throw new CustomException("套餐真在售卖中，不能删除");
        }

        //3.如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(ids);

        //4.删除关系表---setmeal_dish
        // sql语句：drop from setmeal_dish where setmeal_id in(ids中的id)
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setMealDishService.remove(lambdaQueryWrapper);//删除数据
    }

    @Override
    @Transactional
    public SetmealDto getWithDish(Long id) {
        //1.根据套餐id，获取套餐信息
        Setmeal setMeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();

        //2.进行bean属性值的的拷贝，拷贝给setmealDto
        BeanUtils.copyProperties(setMeal,setmealDto);

        //3.获取CategoryId，查询对应的分类名字
        Long categoryId = setMeal.getCategoryId();
        String categoryName = categoryService.getById(categoryId).getName();

        //4.赋值给setmealDto对应的属性 categoryName
        setmealDto.setCategoryName(categoryName);

        //5.根据套餐id，去setmeal_dish表中查找对应的菜品，并封装为一个list
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setMealDishService.list(qw);

        //6.赋值给setmealDto对应的属性 setmealDishes
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

    /**
     * 修改菜品信息
     * @param setmealDto
     */
    @Override
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {
        //1.修改套餐的信息
        this.updateById(setmealDto);

        //2.删除原有套餐所对应的菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        if(setmealDishes != null){
            LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
            qw.eq(SetmealDish::getSetmealId,setmealDto.getId());
            setMealDishService.remove(qw);
        }

        //3.将先修改的菜品信息并保存到setmeal_dish表中
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setMealDishService.saveBatch(setmealDishes);
    }

    /**
     *  单条套餐/多条套餐 起售停售
     * @param status 状态 0停售，1起售
     * @param ids 要启停售的套餐id集合
     */
    @Override
    @Transactional
    public void updateStatus(Integer status, List<Long> ids) {
        //1.根据id找到对应的套餐，并封装成一个list集合
        List<Setmeal> setmeals = this.listByIds(ids);

        //2.取出list集合中的每个元素，对他们的状态进行修改
        setmeals.stream().map((item)->{
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());

        //3.然后根据id依次把套餐信息的修改保存到数据库中
        this.updateBatchById(setmeals);
    }


}
